package Jets.ui.skins
{
   import flash.display.Bitmap;
   import flash.display.BitmapData;
   import flash.events.Event;
   import flash.utils.Dictionary;
   
   import Jets.display.JSprite;
   
   public class BmpSkin extends Skin
   {
	   static var bmps:Array = [];
	   public static var dics:Dictionary = new Dictionary();
	   
	  /**
	  * 位图皮肤
	  */  
      public function BmpSkin(nomal:*, over:*=null, down:*=null,select:*=null,repeat:Boolean=false) 
	  {
         super(nomal,over,down,select,null,repeat);
      }
      
      public static function getBitmap():Bitmap 
	  {
         if(bmps.length > 0)
         {
            bmps.pop();
         }
         return new Bitmap();
      }
      
      public static function recycle(bit:Bitmap) : void 
	  {
         bmps.push(bit);
      }

      override public function draw(event:Event) : void 
	  {
         var bit:BitmapData = null;
         var ui:JSprite = event.target as JSprite;
         switch(ui.state)
         {
            case SkinStates.OVER:
				bit = over;
               break;
            case SkinStates.DOWN:
				bit = down;
               break;
            case SkinStates.SELECTED:
				bit = select;
               break;
            default:
				bit = normal;
         }
         
		 bit = (bit) || (normal);
         if(bit != (dics[ui] as Bitmap).bitmapData)
         {
            (dics[ui] as Bitmap).bitmapData = bit;
			ui.width = bit.width;
			ui.height = bit.height;
         }
		 ui.graphics.clear();
      }
      
      override public function hook(dis:JSprite) : void 
	  {
		  dis.addEventListener(JSprite.DRAW,this.draw);
         var bit:Bitmap = getBitmap();
         if(bit)
         {
            dics[dis] = bit;
            dis.addChildAt(bit,0);
         }
      }
      
      override public function unhook(dis:JSprite) : void 
	  {
		  dis.removeEventListener(JSprite.DRAW,this.draw);
         if(dics[dis])
         {
            recycle(dics[dis]);
            if(dis.contains(dics[dis]))
            {
				dis.removeChild(dics[dis]);
            }
            dics[dis] = null;
         }
      }
   }
}
